package com.polaris.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.polaris.server.mapper.SysMenuMapper;
import com.polaris.server.pojo.SysMenu;
import com.polaris.server.pojo.SysRoleMenu;
import com.polaris.server.mapper.SysRoleMenuMapper;
import com.polaris.server.service.ISysMenuService;
import com.polaris.server.service.ISysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author polaris
 * @since 2021-06-06
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {
    private final SysMenuMapper menuMapper;
    private final SysRoleMenuMapper roleMenuMapper;
    private final ISysMenuService menuService;

    public SysRoleMenuServiceImpl(SysMenuMapper menuMapper, SysRoleMenuMapper roleMenuMapper, ISysMenuService menuService) {
        this.menuMapper = menuMapper;
        this.roleMenuMapper = roleMenuMapper;
        this.menuService = menuService;
    }

    /**
     * 通过roleIdList获取urlSet
     * @param roleList
     * @return
     */
    @Override
    public Set<String> getUrlSet(List<Long> roleList){
        HashSet<String> urlSet = new HashSet<>();
        for (Long role : roleList) {
            SysRoleMenu roleMenu = roleMenuMapper.selectOne(new QueryWrapper<SysRoleMenu>().eq("role_id", role));
            if (roleMenu!=null){
                SysMenu sysMenu = menuMapper.selectById(roleMenu.getMenuId());
                if(sysMenu!=null){
                    urlSet.add(sysMenu.getUrl());
                }
            }
        }
        return urlSet;
    }

    /**
     * 通过roleIdList获取menuList
     * @param roleList
     * @return
     */
    @Override
    public List<SysMenu> getMenuList(List<Long> roleList) {
        List<Long> menuList = new ArrayList<>();
        for (Long roleId : roleList) {
            List<SysRoleMenu> sysRoleMenu = roleMenuMapper.selectList(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));
            if(sysRoleMenu!=null){
                for (SysRoleMenu roleMenu : sysRoleMenu) {
                    menuList.add(roleMenu.getMenuId());
                }
            }
        }

        if(CollUtil.isNotEmpty(menuList)){
            return menuService.getMenuList(menuList);
        }
        return null;
    }
}
